package com.fragrance.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.fragrance.cfg.FragranceJFinalCfg;
import com.fragrance.model.WxUserModel;
import com.fragrance.service.WeChatApiService;
import com.fragrance.service.WeChatUserService;
import com.fragrance.util.Constants;
import com.fragrance.util.Encrypt;
import com.fragrance.util.WeChatHttpUtils;
import com.jfinal.plugin.redis.Redis;

public class WeChatApiServiceImpl implements WeChatApiService {


	private Logger logger = LoggerFactory.getLogger(WeChatApiServiceImpl.class);

	private WeChatUserService weChatUserService = new WeChatUserServiceImpl();

	@Override
	public Map<String, Object> getOpenId(String code) {
		Map<String, Object> result = new HashMap<String, Object>();
		// https://developers.weixin.qq.com/miniprogram/dev/api/api-login.html#wxloginobject
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
		String appid = FragranceJFinalCfg.weChatProp.get("wechat.appid");
		if (StringUtils.isEmpty(appid)) {
			logger.info("请在配置文件wechat.properties配置wechat.appid");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			return result;
		}
		String secret = FragranceJFinalCfg.weChatProp.get("wechat.secret");
		if (StringUtils.isEmpty(secret)) {
			logger.info("请在配置文件wechat.properties配置wechat.secret");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			return result;
		}
		url = url.replace("APPID", appid).replace("SECRET", secret).replace("JSCODE", code);
		try {
			String content = WeChatHttpUtils.sendGet(url);
			logger.info("content = "+  content);
			if (WeChatHttpUtils.checkSuccess(content)) {
				Map<String, String> contentMap = JSON.parseObject(content, Map.class);
				result.put("code", Constants.SUCCESS_CODE);
				result.put("msg", Constants.SUCCESS_MSG);
				String openid = contentMap.get("openid");
				// 每一个用户的会话加密密钥
				String session_key = contentMap.get("session_key");
				boolean flag = weChatUserService.existOpenid(openid);
				Map<String, Object> userInfo = new HashMap<String, Object>();
				userInfo.put("openid", openid);
				userInfo.put("sessionKey", session_key);
				if (flag) {
					//说明用户已经绑定过
					userInfo.put("hashUserInfo", true);
					WxUserModel model = weChatUserService.getWeChatUserInfo(openid);
					// 用户信息
					userInfo.put("id", model.getInt("id"));
					userInfo.put("accountNo", model.getStr("account_no"));
					userInfo.put("nickName", model.getStr("nick_name"));
					userInfo.put("province", model.getStr("province"));
					userInfo.put("city", model.getStr("city"));
					userInfo.put("sex", model.getStr("sex"));
					userInfo.put("country", model.getStr("country"));
				} else {
					//说明用户没有绑定过
					userInfo.put("hashUserInfo", false);
				}
				String token = Encrypt.MD5("wx_" + Encrypt.MD5(openid, "utf-8"));
				userInfo.put("token", token);
				// 添加返回微信用户信息 存放到redis
				Redis.use("users").setex(token, 24 * 60 * 60, JSON.toJSONString(userInfo));
				result.put("code", Constants.SUCCESS_CODE);
				result.put("msg", Constants.SUCCESS_MSG);
				// 该值是密钥不能返回前端
				userInfo.remove("sessionKey");
				result.put("data", userInfo);
				return result;
			} else {
				logger.info("获取微信openid失败content=" + content);
			}
		} catch (Exception e) {
			logger.error("获取openid失败", e);
		}
		result.put("code", Constants.ERROR_CODE);
		result.put("msg", Constants.ERROR_MSG);
		return result;
	}

}
